package com.dsteiner.xelavos.client.controller;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.dsteiner.widgets.client.DateUtilImpl;
import com.dsteiner.widgets.client.IJsUtil;
import com.dsteiner.widgets.client.JsUtil;
import com.dsteiner.widgets.client.ObjectUtil;
import com.dsteiner.widgets.client.Widgets.IFlowPanel;
import com.dsteiner.widgets.client.Widgets.IHTML;
import com.dsteiner.widgets.client.Widgets.IImage;
import com.dsteiner.widgets.client.Widgets.ILazyWidget;
import com.dsteiner.widgets.client.Widgets.IListBox;
import com.dsteiner.widgets.client.Widgets.IScrollPanel;
import com.dsteiner.widgets.client.Widgets.IWidget;
import com.dsteiner.widgets.client.Widgets.IWidgetBuilder;
import com.dsteiner.widgets.client.Widgets.WidgetListenerAdapter;
import com.dsteiner.widgets.client.controller.PopupOverlayController;
import com.dsteiner.widgets.client.domain.ModelObject;
import com.dsteiner.widgets.client.domain.Sort;
import com.dsteiner.widgets.client.event.DataUpdateEvent;
import com.dsteiner.widgets.client.event.EventListener;
import com.dsteiner.widgets.client.event.EventManager;
import com.dsteiner.widgets.client.event.EventManagerImpl;
import com.dsteiner.widgets.client.event.MessageEvent;
import com.dsteiner.widgets.client.model.PaginationModel;
import com.dsteiner.widgets.client.model.PopupOverlayModel;
import com.dsteiner.widgets.client.model.PrefilledTextBoxModel;
import com.dsteiner.widgets.client.model.SuggestBoxModel;
import com.dsteiner.widgets.client.model.SuggestionModel;
import com.dsteiner.widgets.client.rpc.SearchRequest;
import com.dsteiner.xelavos.client.SendMessageWidget.SendMessageModel;
import com.dsteiner.xelavos.client.constants.Constants;
import com.dsteiner.xelavos.client.domain.Job;
import com.dsteiner.xelavos.client.domain.Leisure;
import com.dsteiner.xelavos.client.domain.Product;
import com.dsteiner.xelavos.client.domain.SearchInfo;
import com.dsteiner.xelavos.client.domain.SearchRequestXelavos;
import com.dsteiner.xelavos.client.domain.Service;
import com.dsteiner.xelavos.client.event.CreateObjectEvent;
import com.dsteiner.xelavos.client.event.SavedSearchEvent;
import com.dsteiner.xelavos.client.event.SearchEvent;
import com.dsteiner.xelavos.client.event.SearchInfoEvent;
import com.dsteiner.xelavos.client.event.SearchResultEvent;
import com.dsteiner.xelavos.client.event.SendMessageEvent;
import com.dsteiner.xelavos.client.event.TabSelectionEvent;
import com.dsteiner.xelavos.client.model.AuthenticationModel;
import com.dsteiner.xelavos.client.model.CreateObjectModel;
import com.dsteiner.xelavos.client.model.DataModel;
import com.dsteiner.xelavos.client.model.DisplayModel;
import com.dsteiner.xelavos.client.model.MainTabModel;
import com.dsteiner.xelavos.client.model.SearchModel;
import com.dsteiner.xelavos.client.model.MainTabModel.Tab;
import com.dsteiner.xelavos.client.resources.XelavosImageBundle;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.logical.shared.ResizeEvent;
import com.google.gwt.event.logical.shared.ResizeHandler;
import com.google.gwt.user.client.ui.AbstractImagePrototype;

public class SearchController {

	private AuthenticationModel authenticationModel;
	private IFlowPanel contentPanel;
	private IModelObjectBuilder createJobController;
	private IWidget createJobWidget;
	private IModelObjectBuilder createLeisureController;
	private IWidget createLeisureWidget;
	private IImage createObjectImage;
	private IHTML createObjectLink;
	private CreateObjectModel createObjectModel;
	private PopupOverlayModel createObjectPopupOverlayModel;
	private IWidget createObjectWidget;
	private IModelObjectBuilder createProductController;
	private IWidget createProductWidget;
	private IModelObjectBuilder createServiceController;
	private IWidget createServiceWidget;
	private EventManager eventManager;
	private IJsUtil jsUtil;
	private String lastSearchText;
	private MainTabModel mainTabModel;
	private PaginationModel paginationModel;
	private IWidget paginationWidget;
	private IWidget savedSearchIcon;
	private PopupOverlayModel savedSearchPopupModel;
	private IScrollPanel scrollPanel;
	private IImage searchImage;
	private IWidget searchInfoWidget;
	private SearchModel searchModel;
	private PrefilledTextBoxModel searchTextBoxModel;
	private SendMessageModel sendMessageModel;
	private PopupOverlayModel sendMessagePopupOverlayModel;
	private IHTML sortHtml;
	private IListBox sortListBox;
	private IHTML todaysLeisureLink;
	private IWidgetBuilder widgetBuilder;

	public void registerAuthenticationModel(AuthenticationModel authenticationModel) {
		this.authenticationModel = authenticationModel;
		authenticationModel.addPropertyChangeListener("user", new PropertyChangeListener(){
			public void propertyChange(PropertyChangeEvent evt) {
				updateScrollPanelHeight();
			}
		});
	}

	public void registerContentPanel(IFlowPanel productsContentPanel) {
		this.contentPanel = productsContentPanel;
	}

	public void registerCreateJobController(IModelObjectBuilder createJobController) {
		this.createJobController = createJobController;
	}

	public void registerCreateJobWidget(IWidget createJobWidget) {
		this.createJobWidget = createJobWidget;
	}

	public void registerCreateLeisureController(IModelObjectBuilder createLeisureController) {
		this.createLeisureController = createLeisureController;
	}

	public void registerCreateLeisureWidget(IWidget createLeisureWidget) {
		this.createLeisureWidget = createLeisureWidget;
	}

	public void registerCreateObjectButton(final IImage createObjectButton) {
		this.createObjectImage = createObjectButton;
		createObjectButton.addClickHandler(new ClickHandler(){
			public void onClick(ClickEvent event) {
				jsUtil.trackEvent(Constants.CAT_PUBLISHING, Constants.ACT_CLICKED_CREATE_BUTTON, "tab_"+mainTabModel.getSelectedTab());
				ModelObject createModelObject = createModelObjectFromSearchText();
				eventManager.fireEvent(new CreateObjectEvent(createModelObject));
			}
		});
	}

	public void registerCreateObjectLink(IHTML createObjectLink) {
		this.createObjectLink = createObjectLink;
		createObjectLink.addClickHandler(new ClickHandler(){
			public void onClick(ClickEvent event) {
				jsUtil.trackEvent(Constants.CAT_PUBLISHING, Constants.ACT_CLICKED_CREATE_LINK, "tab_"+mainTabModel.getSelectedTab());
				ModelObject createModelObject = createModelObjectFromSearchText();
				eventManager.fireEvent(new CreateObjectEvent(createModelObject));
			}
		});
	}

	public void registerCreateObjectModel(final CreateObjectModel createObjectModel) {
		this.createObjectModel = createObjectModel;
	}

	public void registerCreateObjectOverlayPopupModel(PopupOverlayModel createProductPopupOverlayModel) {
		this.createObjectPopupOverlayModel = createProductPopupOverlayModel;
	}

	public void registerCreateObjectWidget(IWidget createObjectWidget) {
		this.createObjectWidget = createObjectWidget;
	}

	public void registerCreateProductController(IModelObjectBuilder createProductController) {
		this.createProductController = createProductController;
	}

	public void registerCreateProductWidget(IWidget createProductWidget) {
		this.createProductWidget = createProductWidget;
	}

	public void registerCreateServiceController(IModelObjectBuilder createServiceController) {
		this.createServiceController = createServiceController;
	}

	public void registerCreateServiceWidget(IWidget createServiceWidget) {
		this.createServiceWidget = createServiceWidget;
	}

	public void registerEventManager(EventManager eventManager) {
		this.eventManager = eventManager;
		eventManager.registerListener(CreateObjectEvent.class, new EventListener<CreateObjectEvent>(){
			public void onEvent(CreateObjectEvent event) {
				createObjectModel.setCreateModelObject((ModelObject) event.getObject());
				showCreateObjectPopup();
			}
		});
		eventManager.registerListener(DataUpdateEvent.class, new EventListener<DataUpdateEvent>(){
			public void onEvent(DataUpdateEvent event) {
				createObjectPopupOverlayModel.setVisible(false);
			}
		});
		eventManager.registerListener(SavedSearchEvent.class, new EventListener<SavedSearchEvent>() {
			public void onEvent(SavedSearchEvent event) {
				savedSearchPopupModel.setVisible(false);
			}
		});
		eventManager.registerListener(TabSelectionEvent.class, new EventListener<TabSelectionEvent>() {
			public void onEvent(TabSelectionEvent event) {
				searchTextBoxModel.setText(null);
				Tab tab = event.getTab();
				updateSelectedTab(tab);
				doSearch(tab);
				updateTodaysLeisureLinkVisibility(tab);
			}
		});
		eventManager.registerListener(SearchEvent.class, new EventListener<SearchEvent>(){
			public void onEvent(SearchEvent event) {
				SearchRequest searchRequest = event.getSearchRequest();
				int offset = searchRequest.getOffset();
				updatePaginationModel(offset, searchRequest.getLimit());
				updateSortListBoxSelection(searchRequest.getSort());
				updateSearchTextBox(searchRequest.getText());
			}
		});
		eventManager.registerListener(SearchResultEvent.class, new EventListener<SearchResultEvent>() {
			public void onEvent(SearchResultEvent event) {
				updateVisibility();
			}
		});
		eventManager.registerListener(MessageEvent.class, new EventListener<MessageEvent>() {
			public void onEvent(MessageEvent event) {
				if(Constants.MSG_MESSAGE_SENT.equals(event.getMessage()))
					sendMessagePopupOverlayModel.setVisible(false);
			}
		});
		eventManager.registerListener(SendMessageEvent.class, new EventListener<SendMessageEvent>() {
			public void onEvent(SendMessageEvent event) {
				sendMessageModel.setToUserId(event.getToUserId());
				sendMessageModel.setToUserName(event.getToUserName());
				PopupOverlayController.showAtCenter(sendMessagePopupOverlayModel);
			}
		});

	}

	public void registerJsUtil(IJsUtil jsUtil) {
		this.jsUtil = jsUtil;
		jsUtil.addWindowResizeHandler(new ResizeHandler(){
			public void onResize(ResizeEvent event) {
				updateScrollPanelHeight();
			}
		});
	}
	
	public void registerMainTabModel(MainTabModel mainTabModel) {
		this.mainTabModel = mainTabModel;
	}

	public void registerPaginationModel(final PaginationModel paginationModel) {
		this.paginationModel = paginationModel;
		paginationModel.addPropertyChangeListener("page", new PropertyChangeListener(){
			public void propertyChange(PropertyChangeEvent evt) {
				doSearch();
				jsUtil.trackEvent(Constants.CAT_PAGINATION, Constants.ACT_CLICKED_PAGE_LINK);
			}
		});
		paginationModel.addPropertyChangeListener("itemsPerPage", new PropertyChangeListener(){
			public void propertyChange(PropertyChangeEvent evt) {
				doSearch();
				jsUtil.trackEvent(Constants.CAT_PAGINATION, Constants.ACT_CHANGED_ITEMS_PER_PAGE_LIST_BOX);
			}
		});
	}

	public void registerPaginationWidget(IWidget paginationWidget) {
		this.paginationWidget = paginationWidget;
	}

	public void registerSavedSearchIcon(IImage savedSearchIcon) {
		this.savedSearchIcon = savedSearchIcon;
		savedSearchIcon.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				if(authenticationModel.getUser() == null){
					JsUtil.getInstance().showAlert("Necesita estar logeado para poder guardar busquedas");
					return;
				}
					
				PopupOverlayController.showAtCenter(savedSearchPopupModel);
			}
		});
	}

	public void registerSavedSearchPopupModel(PopupOverlayModel savedSearchPopupModel) {
		this.savedSearchPopupModel = savedSearchPopupModel;
	}

	public void registerScrollPanel(IScrollPanel productsScrollPanel) {
		this.scrollPanel = productsScrollPanel;
	}

	public void registerSearchButton(IImage searchButton) {
		this.searchImage = searchButton;
		searchButton.addClickHandler(new ClickHandler(){
			public void onClick(ClickEvent event) {
				jsUtil.trackEvent(Constants.CAT_SEARCH, Constants.ACT_CLICKED_SEARCH_BUTTON, 
						"Tab "+mainTabModel.getSelectedTab());
				doSearch();
			}
		});
	}

	public void registerSearchInfoWidget(IWidget searchInfoWidget) {
		this.searchInfoWidget = searchInfoWidget;
	}

	public void registerSearchModel(final SearchModel searchModel) {
		this.searchModel = searchModel;
		searchModel.addPropertyChangeListener("results", new PropertyChangeListener(){
			public void propertyChange(PropertyChangeEvent evt) {
				updateResults();
			}
		});
		searchModel.addPropertyChangeListener("count", new PropertyChangeListener(){
			public void propertyChange(PropertyChangeEvent evt) {
				paginationModel.setCount(searchModel.getCount());
			}
		});
	}

	public void registerSearchTextBoxModel(final SuggestBoxModel searchTextBoxModel) {
		this.searchTextBoxModel = searchTextBoxModel;
		searchTextBoxModel.addPropertyChangeListener("keyCode", new PropertyChangeListener(){
			public void propertyChange(PropertyChangeEvent evt) {
				if(searchTextBoxModel.getKeyCode() == KeyCodes.KEY_ENTER){
					jsUtil.trackEvent(Constants.CAT_SEARCH, Constants.ACT_TYPED_ENTER_IN_SEARCH_BOX, 
							"Tab "+mainTabModel.getSelectedTab());
					doSearch();
				}
			}
		});
		searchTextBoxModel.addPropertyChangeListener("choosenSuggestion", new PropertyChangeListener(){
			public void propertyChange(PropertyChangeEvent evt) {
				SuggestionModel choosenSuggestion = searchTextBoxModel.getChoosenSuggestion();
				if(choosenSuggestion != null){
					searchTextBoxModel.setText(choosenSuggestion.getSuggestion().getDisplayText());
					doSearch();
				}
			}
		});
	}
	
	public void registerSearchWidget(ILazyWidget shoppingWidget) {
		shoppingWidget.addWidgetListener(new WidgetListenerAdapter(){
			@Override
			public void onAttach(IWidget widget) {
				updateVisibility();
				updateScrollPanelHeight();
				updateSelectedTab(mainTabModel.getSelectedTab());
				updateResults();
				updateTodaysLeisureLinkVisibility(mainTabModel.getSelectedTab());
				DataModel.SEARCH_REQUEST_DEFAULT.setClassName(mainTabModel.getSelectedTab().getClassName());
				EventManagerImpl.getInstance().fireEvent(new SearchEvent(DataModel.SEARCH_REQUEST_DEFAULT));
			}
		});
	}
	
	public void registerSendMessageModel(SendMessageModel sendMessageModel) {
		this.sendMessageModel = sendMessageModel;
	}

	public void registerSendMessagePopupOverlayModel(PopupOverlayModel sendMessagePopupOverlayModel) {
		this.sendMessagePopupOverlayModel = sendMessagePopupOverlayModel;
	}
	

	public void registerSortHtml(IHTML sortHtml) {
		this.sortHtml = sortHtml;
	}

	public void registerSortListBox(final IListBox sortListBox) {
		this.sortListBox = sortListBox;
		sortListBox.addChangeHandler(new ChangeHandler(){
			public void onChange(ChangeEvent event) {
				paginationModel.setPage(0);
				String sort = sortListBox.getSelectedValue();
				doSearch();
				jsUtil.trackEvent(Constants.CAT_SEARCH, Constants.ACT_CHANGED_SORT, 
						"Tab "+mainTabModel.getSelectedTab());
			}
		});
	}

	public void registerTodaysLeisureLink(IHTML todaysLeisureLink) {
		this.todaysLeisureLink = todaysLeisureLink;
		todaysLeisureLink.addClickHandler(new ClickHandler(){
			public void onClick(ClickEvent event) {
				searchTextBoxModel.setText(DateUtilImpl.getInstance().formatDateSpanish(new Date()));
				doSearch();
			}
		});
	}

	public void registerWidgetBuilder(IWidgetBuilder productWidgetBuilder) {
		this.widgetBuilder = productWidgetBuilder;
	}

	private ModelObject createModelObjectFromSearchText() {
		ModelObject createModelObject = null;
		String text = searchTextBoxModel.isEdited() ? searchTextBoxModel.getText() : null;
		if(mainTabModel.isShoppingTabSelected()){
			createModelObject = new Product();
			((Product)createModelObject).setName(text);
		}
		else if(mainTabModel.isServicesTabSelected()){
			createModelObject = new Service();
			((Service)createModelObject).setType(text);
		}
		else if(mainTabModel.isLeisureTabSelected()){
			createModelObject = new Leisure();
			((Leisure)createModelObject).setName(text);
		}
		else if(mainTabModel.isJobsTabSelected()){
			createModelObject = new Job();
			((Job)createModelObject).setName(text);
		}
		return createModelObject;
	}
	
	private void doSearch() {
		doSearch(mainTabModel.getSelectedTab());
	}

	private void doSearch(Tab tab) {
		String text = searchTextBoxModel.isEdited() ? searchTextBoxModel.getText() : null;
		if(!ObjectUtil.equals(text, lastSearchText)){
			paginationModel.setPage(0);
		}
		boolean isLeisureDateSearch = mainTabModel.isLeisureTabSelected() && DateUtilImpl.getInstance().isDateSpanish(text);
		String sort = sortListBox.getSelectedValue();
		SearchRequestXelavos searchRequest = new SearchRequestXelavos();
		if(isLeisureDateSearch){
			searchRequest.setType(SearchRequest.TYPE_BETWEEN);
			searchRequest.setFromFieldName("eventDateAsDate");
			searchRequest.setToFieldName("eventDateUntilAsDate");
		}
		else
			searchRequest.setType(text != null ? SearchRequest.TYPE_PREFIX : SearchRequest.TYPE_ALL);
		searchRequest.setText(text);
		searchRequest.setClassName(tab.getClassName());
		searchRequest.setSort(new Sort(sort));
		searchRequest.setLimit(paginationModel.getItemsPerPage());
		searchRequest.setOffset(paginationModel.getOffset());
		EventManagerImpl.getInstance().fireEvent(new SearchEvent(searchRequest));
		lastSearchText = text;
	}

	private void showCreateObjectPopup() {
		if(authenticationModel.getUser() == null){
			jsUtil.trackEvent(Constants.CAT_PUBLISHING, Constants.ACT_MSG_SHOWN, Constants.LBL_NOT_LOGGED_IN);
			jsUtil.showAlert("necesita estar logeado para ingresar algo");
			return;
		}
		PopupOverlayController.showAtCenter(createObjectPopupOverlayModel);
	}

	private void updatePaginationModel(int offset, int limit) {
		paginationModel.setItemsPerPage(limit);
		paginationModel.setPage(offset / limit);
	}

	private void updateResults() {
		contentPanel.clear();
		List<ModelObject> results = searchModel.getResults();
		boolean isEmptyResults = results == null || results.isEmpty();
		if(isEmptyResults)
			return;
		
		for (ModelObject modelObject : results) {
			DisplayModel displayModel = new DisplayModel();
			displayModel.setModelObject(modelObject);
			IWidget widget = widgetBuilder.createWidget(displayModel);
			contentPanel.add(widget);
		}
	}

	private void updateScrollPanelHeight() {
		int clientHeight = jsUtil.getClientHeight();
		int height = clientHeight - Constants.Util.getHeaderHeight(authenticationModel.getUser()) - Constants.HEIGHT_TAB - 110;
		scrollPanel.setHeight(height+"px");
	}

	private void updateSearchTextBox(String search) {
		searchTextBoxModel.setText(search);
	}

	private void updateSelectedTab(Tab tab) {
		String createObjectText = "";
		String searchText = "";
		String searchBoxDefaultText = "";
		IWidget contentWidget = null;
		AbstractImagePrototype createObjectIcon = null;
		IModelObjectBuilder modelObjectBuilder = null;
		List<String> sortItems = new ArrayList<String>();
		List<String> sortValues = new ArrayList<String>();
		sortItems.add("fecha");
		sortValues.add(new Sort("registeredDate", false).toString());
		
		if(MainTabModel.TAB_ID_SHOPPING.equals(tab)){
			createObjectText = "producto";
			createObjectIcon = XelavosImageBundle.Util.getInstance().shoppingIcon();
			searchText = "buscar productos";
			searchBoxDefaultText = "<span class=\"main\">nombre</span> o <span class=\"main\">marca</span> o " +
					"<span class=\"main\">modelo</span> del producto";
			contentWidget = createProductWidget;
			modelObjectBuilder = createProductController;
			sortItems.add("precio: ascendente");
			sortValues.add(new Sort("price", true).toString());
			sortItems.add("precio: descendente");
			sortValues.add(new Sort("price", false).toString());
			sortItems.add("valoracion de usuarios");
			sortValues.add(new Sort("rating", false).toString());
			sortItems.add("nombre: ascendente");
			sortValues.add(new Sort("name", true).toString());
			sortItems.add("nombre: descendente");
			sortValues.add(new Sort("name", false).toString());
		}
		else if(MainTabModel.TAB_ID_JOB.equals(tab)){
			createObjectText = "trabajo";
			createObjectIcon = XelavosImageBundle.Util.getInstance().jobIcon();
			searchText = "buscar trabajo";
			searchBoxDefaultText = "<span class=\"main\">nombre</span> o <span class=\"main\">empleador</span> del trabajo";
			contentWidget = createJobWidget;
			modelObjectBuilder = createJobController;
			sortItems.add("valoracion de usuarios");
			sortValues.add(new Sort("rating", false).toString());
			sortItems.add("nombre: ascendente");
			sortValues.add(new Sort("name", true).toString());
			sortItems.add("nombre: descendente");
			sortValues.add(new Sort("name", false).toString());
		}
		else if(MainTabModel.TAB_ID_LEISURE.equals(tab)){
			createObjectText = "recreacion";
			createObjectIcon = XelavosImageBundle.Util.getInstance().leisureIcon();
			searchText = "buscar recreaciones";
			searchBoxDefaultText = "<span class=\"main\">nombre</span> o <span class=\"main\">lugar</span> o " +
					"<span class=\"main\">fecha</span> de la recreacion";
			contentWidget = createLeisureWidget;
			modelObjectBuilder = createLeisureController;
			sortItems.add("valoracion de usuarios");
			sortValues.add(new Sort("rating", false).toString());
			sortItems.add("nombre: ascendente");
			sortValues.add(new Sort("name", true).toString());
			sortItems.add("nombre: descendente");
			sortValues.add(new Sort("name", false).toString());
		}
		else if(MainTabModel.TAB_ID_SERVICES.equals(tab)){
			createObjectText = "servicio";
			createObjectIcon = XelavosImageBundle.Util.getInstance().serviceIcon();
			searchText = "buscar servicios";
			searchBoxDefaultText = "<span class=\"main\">nombre</span> o <span class=\"main\">tipo</span> del servicio";
			contentWidget = createServiceWidget;
			modelObjectBuilder = createServiceController;
			sortItems.add("valoracion de usuarios");
			sortValues.add(new Sort("rating", false).toString());
			sortItems.add("nombre: ascendente");
			sortValues.add(new Sort("name", true).toString());
			sortItems.add("nombre: descendente");
			sortValues.add(new Sort("name", false).toString());
			sortItems.add("tipo: ascendente");
			sortValues.add(new Sort("type", true).toString());
			sortItems.add("tipo: descendente");
			sortValues.add(new Sort("type", false).toString());
		}
		else if(MainTabModel.TAB_ID_COMMUNITY.equals(tab)){
			createObjectText = "amigo";
			createObjectIcon = XelavosImageBundle.Util.getInstance().communityIcon();
			searchText = "buscar miembros";
			searchBoxDefaultText = "<span class=\"main\">nombre</span> del miembro";
			// TODO - change to createUserWidget
			contentWidget = createProductWidget;
			modelObjectBuilder = createProductController;
			sortItems.add("nombre: ascendente");
			sortValues.add("nickName:asc");
			sortItems.add("nombre: descendente");
			sortValues.add("nickName:desc");
		}
		searchModel.setResults(null);
		createObjectImage.setVisible(!mainTabModel.isFriendsTabSelected());
		sortListBox.setItems(sortItems, sortValues);
		searchTextBoxModel.setDefaultText(searchBoxDefaultText);
		searchImage.setTitle(searchText);
		createObjectImage.setTitle("publique "+createObjectText);
		createObjectModel.setContentWidget(contentWidget);
		createObjectModel.setModelObjectBuilder(modelObjectBuilder);
		createObjectModel.setTitle(createObjectText);
		createObjectModel.setIcon(createObjectIcon);
	}

	private void updateSortListBoxSelection(Sort sort) {
		if(sort == null)
			return;
		String sortAsString = sort.toString();
		for (int i = 0; i < sortListBox.getItemCount(); i++) {
			String value = sortListBox.getValue(i);
			if(sortAsString.equals(value)){
				sortListBox.setSelectedIndex(i);
				break;
			}
		}
	}

	private void updateTodaysLeisureLinkVisibility(Tab tab) {
		todaysLeisureLink.setVisible(MainTabModel.TAB_ID_LEISURE.equals(tab));
	}

	private void updateVisibility() {
		SearchResultEvent searchResultEvent = eventManager.getEvent(SearchResultEvent.class);
		List<ModelObject> results = searchResultEvent != null ? searchResultEvent.getSearchResults().getObjects() : null;
		boolean isEmptyResults = results == null || results.isEmpty();
		paginationWidget.setVisible(!isEmptyResults && results.size() > 1);
		sortHtml.setVisible(!isEmptyResults && results.size() > 1);
		sortListBox.setVisible(!isEmptyResults && results.size() > 1);
		createObjectLink.setVisible(
				!mainTabModel.isFriendsTabSelected() && 
				searchTextBoxModel.isEdited() && 
				isEmptyResults);
		savedSearchIcon.setVisible(!isEmptyResults && searchTextBoxModel.isEdited());
		SearchInfoEvent searchInfoEvent = eventManager.getEvent(SearchInfoEvent.class);
		SearchInfo searchInfo = searchInfoEvent != null ? searchInfoEvent.getSearchInfo() : new SearchInfo();
		searchInfoWidget.setVisible(isEmptyResults && !searchInfo.isEmpty());
	}

}
